// 完整的API服务层 - 统一管理所有API请求
import { getApiUrl, API_ENDPOINTS, getCurrentConfig } from '../config/api.js'

class ApiService {
  constructor() {
    this.config = getCurrentConfig()
    this.baseConfig = {
      headers: {
        'Content-Type': 'application/json',
      },
    }
  }

  // 统一的请求方法，支持重试机制
  async request(endpoint, options = {}) {
    const url = getApiUrl(endpoint)
    const config = {
      ...this.baseConfig,
      ...options,
    }

    for (let attempt = 1; attempt <= this.config.retryCount; attempt++) {
      try {
        const response = await fetch(url, config)
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const data = await response.json()
        return data
      } catch (error) {
        console.error(`API请求失败 [${endpoint}] 第${attempt}次尝试:`, error)
        
        if (attempt === this.config.retryCount) {
          throw new Error(`API请求失败: ${error.message}`)
        }
        
        // 指数退避延迟
        await this.delay(this.config.retryDelay * Math.pow(2, attempt - 1))
      }
    }
  }

  // 延迟函数
  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
  }

  // GET请求
  async get(endpoint) {
    return this.request(endpoint, { method: 'GET' })
  }

  // POST请求
  async post(endpoint, data) {
    return this.request(endpoint, {
      method: 'POST',
      body: JSON.stringify(data),
    })
  }

  // PUT请求
  async put(endpoint, data) {
    return this.request(endpoint, {
      method: 'PUT',
      body: JSON.stringify(data),
    })
  }

  // DELETE请求
  async delete(endpoint) {
    return this.request(endpoint, { method: 'DELETE' })
  }

  // ========== 热点数据相关API ==========
  
  // 获取热点数据
  async getHotspots() {
    return this.get(API_ENDPOINTS.HOTSPOTS)
  }

  // 立即获取数据
  async fetchNow() {
    return this.post(API_ENDPOINTS.FETCH_NOW)
  }

  // 刷新数据
  async refreshData() {
    return this.post(API_ENDPOINTS.REFRESH_HOTSPOTS)
  }

  // ========== 文案生成相关API ==========
  
  // 生成多平台文案
  async generateCopywriting(data) {
    return this.post(API_ENDPOINTS.COPYWRITING_GENERATE, data)
  }

  // 获取文案历史记录
  async getCopywritingHistory() {
    return this.get(API_ENDPOINTS.COPYWRITING_HISTORY)
  }

  // ========== 趋势分析相关API ==========
  
  // 获取完整趋势分析数据
  async getTrendAnalysis(options = {}) {
    return this.post(API_ENDPOINTS.TRENDS_ANALYZE, options)
  }

  // 获取词云数据
  async getWordCloud() {
    return this.get(API_ENDPOINTS.TRENDS_WORDCLOUD)
  }

  // 获取趋势统计数据
  async getTrendStats() {
    return this.get(API_ENDPOINTS.TRENDS_STATS)
  }

  // ========== 发布相关API ==========
  
  // 执行内容发布
  async publishContent(data) {
    return this.post(API_ENDPOINTS.PUBLISH_EXECUTE, data)
  }

  // 测试发布功能
  async testPublish(data) {
    return this.post(API_ENDPOINTS.PUBLISH_TEST, data)
  }

  // ========== 系统相关API ==========
  
  // 健康检查
  async healthCheck() {
    return this.get(API_ENDPOINTS.HEALTH_CHECK)
  }

  // 获取系统信息
  async getSystemInfo() {
    return this.get(API_ENDPOINTS.SYSTEM_INFO)
  }

  // ========== 工具方法 ==========
  
  // 检查API服务是否可用
  async isServiceAvailable() {
    try {
      await this.healthCheck()
      return true
    } catch (error) {
      console.warn('API服务不可用:', error.message)
      return false
    }
  }

  // 获取API配置信息（用于调试）
  getApiConfig() {
    return {
      baseURL: this.config.baseURL,
      timeout: this.config.timeout,
      retryCount: this.config.retryCount,
      environment: process.env.NODE_ENV || 'development'
    }
  }
}

// 创建单例实例
const apiService = new ApiService()

export default apiService
